<?php

namespace app\admin\validate;

use app\validate\BaseValidate;

class Product extends BaseValidate
{
    /**
     * 定义验证规则
     * 格式：'字段名'=>['规则1','规则2'...]
     *"specs":[{"specs_value_id":"2,4","price":"1","stock":1}]
     * @var array
     */
    protected $rule = [
        'id' => 'number',
        'name' => 'require',
        'cat_id' => 'require|number',
        'image' => 'require',
        'price' => 'require',
        'slide_image' => 'require',
        'stock' => 'require',
        'is_hot' => 'in:0,1',
        'spec_type' => 'require|number',
        'specs'=>'require|checkSpecs'
    ];

    protected $specsRule=[
        'specs_value_id'=>'require|isCommaString',
        'price'=>'require',
        'stock'=>'require'
    ];
    protected $specesMessage=[
        'specs_value_id'=>'商品规格id未填写',
       'price.require'=>'商品规格价格未填写',
       'stock.require'=>'商品库规格库存未填写'
    ];
    /**
     * 定义错误信息
     * 格式：'字段名.规则名'=>'错误信息'
     *
     * @var array
     */
    protected $message = [
        'name'=>'商品名称不能为空'
    ];
    /**
     * 定义验证场景
     * 格式：'场景名'=>['规则1','规则2',...]
     *
     * @var array
     */
    protected $scene = [
        'save' => ['cat_id', 'name','image','price','slide_image','stock','is_hot','spec_type','specs'],
        'delete' => ['id'],
        'update' => ['id', 'cat_id', 'name','image','price','slide_image','stock','is_hot','spec_type','specs'],
        'read' => ['id']
    ];
    /**
     * 自定义验证方法
     */
    protected function checkSpecs($value,$rule='',$data='',$field='')
    {
        if(isset($value) && !is_array($value))
        {
            return $field.'规格类型错误';
        }
        
        $validate=new Product();
        $validate->message=$this->specesMessage;
        foreach ($value as $item)
        {
            if(!is_array($item))
            {
                return $field.'规格数据格式错误';
            }
           
            $result=$validate->check($item,$this->specsRule);
            if(!$result)
            {
                throw new \Exception($validate->error);
            }
        }
        return true;
    }
}
